package com.mark;

import java.util.*;

/**
 * Created by Choisaaaa on 2018/9/6.
 * Collections的使用demo
 */


class Student{//待排序的实体类
    private String name ;//姓名
    private int age;//年龄

    public Student(String name,int age){//构造函数
        this.name = name;
        this.age = age;
    }
    public int getAge() {
        return age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
public class Test {

    private void sort(){
        //数据准备
        Student student1 = new Student("Mark" , 23);
        Student student2 = new Student("Choisaaa",19);
        Student student3 = new Student("Allen",24);
        List<Student> list = new ArrayList<Student>();
        list.add(student1);
        list.add(student2);
        list.add(student3);

        //自定排序规则，按照年龄从小到大排序
        Collections.sort(list, new Comparator<Student>() {
            public int compare(Student student1, Student student2) {
                int age1 = student1.getAge();
                int age2 = student2.getAge();
                return age1 - age2;
            }
        });
        for (Student student : list) {
            System.out.println(student);
        }
    }

    public static void main(String[] args) {
        Test test = new Test();
        test.sort();
    }
}
